//
//  MessageViewController.m
//  cliqset
//
//  Created by David Hinson on 3/30/09.
//  Copyright 2009 Cliqset, Inc.. All rights reserved.
//

#import "MessageViewController.h"
#import "cliqsetAppDelegate.h"
#import "Message.h"
#import "ChooseRecipientViewController.h"

@implementation MessageViewController

@synthesize hoverView;
@synthesize messagesTable;

@synthesize mySegControl;
@synthesize filter;

// Setup the segmented control
-(void)setupSegmentedControl {
	UIColor* myOrange			= [UIColor colorWithRed:255.0/255.0 green:155.0/255.0 blue:5.0/255.0 alpha:1.0];
	
	[self.mySegControl addTarget:self action:@selector(segmentTouched:) forControlEvents:UIControlEventValueChanged];
	
	self.mySegControl.tintColor = myOrange;
}

// Determine whether to display cell
-(BOOL)displayMe:(int)row {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	Message *message = (Message *)[myApp.messages objectAtIndex:row];
	
	switch(self.mySegControl.selectedSegmentIndex) {
		case 0:
			if (![message.sender.userIdentifier isEqualToString:myApp.userString]) {return true;}
			break;
		case 1:
			if ([message.sender.userIdentifier isEqualToString:myApp.userString]) {return true;}
			break;
		default:
			break;
	}
	
	return false;
}

// Load filter
-(void)loadFilter {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	[self.filter removeAllObjects];
	
	NSMutableString * filterEntry;
	for (int x=0; x<[myApp.messages count]; x++) {
		if ([self displayMe:x]) {
			filterEntry = (NSMutableString*)[@"" stringByAppendingFormat:@"%d", x];
			[self.filter addObject:filterEntry];
		}
	}
}

// reset segment control
-(void)resetSegment {
	self.mySegControl.selectedSegmentIndex = 0;
}

// Segmented control has been touched
-(IBAction)segmentTouched:(id)someObject {
	
	[self loadFilter];
	
	[self showHoverView:YES];
	[self.messagesTable reloadData];
	[self showHoverView:NO];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.messagesTable.backgroundColor = [UIColor whiteColor];
	
	self.filter = [[NSMutableArray alloc] init];
	
	[self setupSegmentedControl];
	
	// Load filter
	[self loadFilter];
	
    hoverView.center   = [self view].center;
	
	[[self view] addSubview:hoverView];
    [[self view] bringSubviewToFront:hoverView];
	
	[self insertLogoArtIntoTitle];
}

// Compose message
-(IBAction)composeMessage:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];

	UIBarButtonItem *backBar = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleDone target:nil action:nil];
	self.navigationItem.backBarButtonItem = backBar;	
	[backBar release];
	
	[myApp slideRecipientsIn];
}

- (void)showHoverView:(BOOL)show
{
	// fade animate the view out of view by affecting its alpha
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.40];
    
	if (show)
	{
		hoverView.alpha = 0.85;
	}
	else
	{
		hoverView.alpha = 0.0;
	}
	
	[UIView commitAnimations];
}

-(void)insertLogoArtIntoTitle {
	
	UIColor* myOrange			= [UIColor colorWithRed:255.0/255.0 green:155.0/255.0 blue:5.0/255.0 alpha:1.0];
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	UINavigationController* nc;
	
	for( UIViewController* vc in [myApp tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Messages"]) {
			nc = (UINavigationController *)vc;
			nc.navigationBar.tintColor = myOrange;
			break;
		}
	}
}

#pragma mark ---- table handling ----

// Number of table sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

// Return rows in table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if ([myApp.messages count] == 0) {[self showHoverView:NO];}
	
	return [filter count];
}

// Set row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	NSString * offset = [self.filter objectAtIndex:indexPath.row];

	if ([self displayMe:[offset intValue]]) {
		
		// Per Darren
		return 63;
		
		cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
		Message * message = (Message *)[myApp.messages objectAtIndex:[offset intValue]];
		
		CGSize constraintSize;
		constraintSize.width  = 220.0f;
		constraintSize.height = MAXFLOAT;
		
		CGSize offsetY1    = [[@"" stringByAppendingFormat:@"%@ %@", message.sender.givenName == nil ? @"" : message.sender.givenName , message.sender.familyName == nil ? @"" : message.sender.familyName] sizeWithFont:[UIFont boldSystemFontOfSize:14] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
		CGSize offsetY2    = [message.subject sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
		return offsetY1.height + offsetY2.height + 22;
		}
	else {
		return 0;
		}
}

float min(float a, float b) {
	if (a<=b) {return a;} else {return b;}
}

// Draw cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	NSData      *imageData;
	UIImageView *showImage;
	UILabel     *nameLabel;
	UILabel     *actionLabel;
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
    
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];
    [cell backgroundView].opaque=YES;
    [cell backgroundView].clearsContextBeforeDrawing;
	
   	[cell setSelectionStyle:UITableViewCellSelectionStyleGray];	
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	cell.contentView.backgroundColor = [UIColor whiteColor];
	
	// Safety value
	if (indexPath.row >= ([myApp.messages count])) {return cell;}
	
	self.messagesTable.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
	
	UIColor* textColor = [UIColor colorWithRed:62.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1.0];	
	
	NSString * offset = [self.filter objectAtIndex:indexPath.row];
	Message * message = (Message *)[myApp.messages objectAtIndex:[offset intValue]];
	
	NSDate * tsDate           = [myApp dateFromISO8601:message.timeSent];
	NSString * timeDesc		  = [NSString stringWithFormat:@"%@", [myApp describeEventTimeStamp:tsDate]];
		
	// Fonts for labels
	UIFont* eeeny_teeny_font  = [UIFont systemFontOfSize:10];
	UIFont* large_font        = [UIFont systemFontOfSize:14];
	UIFont* bold_large_font   = [UIFont boldSystemFontOfSize:14];
		
	CGSize constraintSize;
	constraintSize.width      = 220.0f;
	constraintSize.height     = MAXFLOAT;	
	CGSize offsetX            = [timeDesc sizeWithFont:eeeny_teeny_font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeTailTruncation];
		
	// Time stamp
	UILabel * timestamp       = [[UILabel alloc] initWithFrame:CGRectMake(30, cell.frame.size.height, offsetX.width, offsetX.height)];
	timestamp.font            = eeeny_teeny_font;
	timestamp.textColor       = [UIColor grayColor];
	timestamp.backgroundColor = [UIColor clearColor];
	timestamp.text            = timeDesc;
		
	imageData         = message.sender.avatarBlob;
	UIImage * graphic = (UIImage*)[[UIImage alloc] initWithData:imageData];
	showImage         = [[UIImageView alloc] initWithFrame:CGRectMake(5.0, ((54-(40 * graphic.size.height / graphic.size.width))/2.0), 40.0, 40.0 * (graphic.size.height / graphic.size.width))];		
	showImage.image   = graphic;
	[graphic release];
	
	UIView * imageBackground  = [[UIView alloc] init];
	CGRect adjFrame           = showImage.frame;
	adjFrame.origin.x--;
	adjFrame.origin.y--;
	adjFrame.size.height+=2;
	adjFrame.size.width+=2;
	imageBackground.backgroundColor = [UIColor grayColor];
	imageBackground.frame     = adjFrame;
	[cell addSubview:imageBackground];
	[imageBackground release];
	
	// Allocate labels
	nameLabel      = [[UILabel alloc] initWithFrame:CGRectMake(50.0,  4, 240.0, 20.0)];
			
	CGSize offset1 = [[@"" stringByAppendingFormat:@"%@", message.subject] sizeWithFont:large_font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeTailTruncation];
			
	// actionLabel    = [[UILabel alloc] initWithFrame:CGRectMake(50.0, 24, offset1.width,  offset1.height)];
	actionLabel    = [[UILabel alloc] initWithFrame:CGRectMake(50.0, 24, 220,  20)];
			
	CGRect newFrame = CGRectMake(50, 24 + min(20, offset1.height), timestamp.frame.size.width, timestamp.frame.size.height);
	timestamp.frame = newFrame;
			
	if (![message.read isEqualToString:@"false"]) {
		nameLabel.font  = large_font;
		} 
	else {
		nameLabel.font  = bold_large_font;
		}
			
	// Build Name Label
	nameLabel.text            = [@"" stringByAppendingFormat:@"%@ %@", message.sender.givenName == nil ? @"" : message.sender.givenName , message.sender.familyName == nil ? @"" : message.sender.familyName];
	actionLabel.text          = [@"" stringByAppendingFormat:@"%@", message.subject];
	actionLabel.font          = large_font;
	actionLabel.numberOfLines = 1;
	actionLabel.lineBreakMode = UILineBreakModeTailTruncation;
		
	showImage.opaque          = NO;    
		
	nameLabel.backgroundColor        = [UIColor clearColor];
	actionLabel.backgroundColor      = [UIColor clearColor];
		
	// Set text color
	nameLabel.textColor       = textColor;
	actionLabel.textColor     = textColor;
	cell.textColor            = textColor;
		
	// Set label in cell
	[cell addSubview:nameLabel];		
	// Set label in cell
	[cell addSubview:actionLabel];	
	// Add image to cell
	[cell addSubview:showImage];
		
	// Add time stamp
	[cell addSubview:timestamp];
		
	// Cleanup our junk
	[timestamp release];
	[showImage release];
	[nameLabel release];
	[actionLabel release];
		
	return cell;
}

-(void)reloadData {
	[self loadFilter];
	[self.messagesTable reloadData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	UITableViewCell *hitCell = [tableView cellForRowAtIndexPath:indexPath];	
    [hitCell setSelected:NO animated:YES];
	
	UIBarButtonItem *backBar = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleDone target:nil action:nil];
	self.navigationItem.backBarButtonItem = backBar;	
	[backBar release];
	
	NSString * offset = [self.filter objectAtIndex:indexPath.row];
	Message * message = (Message *)[myApp.messages objectAtIndex:[offset intValue]];
	
	[myApp showMessagesHoverView:YES];
	[myApp.cliqset getMessage:message.messageIdentifier messageIndex:[offset intValue]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
}

- (void)dealloc {
	[mySegControl release];
	[filter release];
	[messagesTable release];
	[hoverView release];
    [super dealloc];
}


@end
